package mcom.xmks.bluetooth.mesh.dialog;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;

import mcom.xmks.bluetooth.mesh.R;
import mcom.xmks.bluetooth.mesh.storage.GroupItem;
import mcom.xmks.bluetooth.mesh.storage.GroupStorageUtil;
import mcom.xmks.bluetooth.mesh.utils.ToastUtil;

public class AddNodeToGroupDialog extends BaseDialogFragment {
    private OnSelectGroupListener listener=null;
    private Spinner spGroup;
    private TextView cancel,confirm;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.dialog_add_node_to_group,null);
        spGroup=view.findViewById(R.id.spGroup);
        cancel=view.findViewById(R.id.cancel);
        confirm=view.findViewById(R.id.confirm);
        initWidget();
        return view;
    }

    protected final void initWidget(){
      List<GroupItem> allGroup= GroupStorageUtil.getAllGroup();
      List<String> s=new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            allGroup.forEach(groupItem -> {
                s.add(String.format(Locale.getDefault(),"%04X",groupItem.getAddress()));
            });
        }else{
            for(GroupItem groupItem : allGroup){
                s.add(String.format(Locale.getDefault(),"%04X",groupItem.getAddress()));
            }
        }
        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(requireContext(),R.layout.item_spinner,s);
        arrayAdapter.setDropDownViewResource(R.layout.item_spinner);
        spGroup.setAdapter(arrayAdapter);
        spGroup.setSelection(0);
        cancel.setOnClickListener(v -> {
            dismiss();
        });
        confirm.setOnClickListener(v -> {
            check();
        });
    }
    private void check(){
        if(spGroup.getSelectedItem()==null){
            showToast("Group为空");
            return;
        }
        String s= (String) spGroup.getSelectedItem();
        int toInt=Integer.parseInt(s,16);
        listener.onSelectGroup(toInt);
        dismiss();
    }
    public void setSelectGroupListener(OnSelectGroupListener listener){
       this.listener=listener;
    }
    public interface OnSelectGroupListener{
        void onSelectGroup(int address);
    }
    public void showToast(String message){
        ToastUtil.create(requireActivity(),message);
    }
}
